package com.ths.inputservice.utils;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RtspHistoryManager {
    private static final String PREFS_NAME = "rtsp";
    private static final String HISTORY_KEY_PREFIX = "history_";
    private static final int MAX_HISTORY_SIZE = 10;

    public static List<String> getHistory(Context context, int channelId) {
        SharedPreferences sp = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        Set<String> historySet = sp.getStringSet(HISTORY_KEY_PREFIX + channelId, new HashSet<>());
        List<String> historyList = new ArrayList<>(historySet);
        return historyList;
    }

    public static void addToHistory(Context context, int channelId, String url) {
        if (url == null || url.trim().isEmpty()) {
            return;
        }

        SharedPreferences sp = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        Set<String> historySet = new HashSet<>(sp.getStringSet(HISTORY_KEY_PREFIX + channelId, new HashSet<>()));
        
        // 如果已存在，先移除旧的
        historySet.remove(url);
        
        // 转为列表以控制大小
        List<String> historyList = new ArrayList<>(historySet);
        
        // 如果达到最大数量，删除最早的
        if (historyList.size() >= MAX_HISTORY_SIZE) {
            historyList.remove(0);
        }
        
        // 添加新的URL
        historyList.add(url);
        
        // 保存回SharedPreferences
        sp.edit().putStringSet(HISTORY_KEY_PREFIX + channelId, new HashSet<>(historyList)).apply();
    }
}
